#include "sqlite3Impl.h"  
#include <iostream>


bool Sqlite3Impl::open(char* filename)
{
    if(sqlite3_open(filename, &database) == SQLITE_OK)
        return true;
    return false;
}

void* Sqlite3Impl::prepare(char* query)
{
    sqlite3_stmt *statement;
    if(sqlite3_prepare_v2(database, query, -1, &statement, 0) == SQLITE_OK)
    {
        return (void*)statement;
    }
    string error = sqlite3_errmsg(database);

    return 0;
}

void Sqlite3Impl::bind(void* stat, int position, char*text,int len){
     sqlite3_bind_text((sqlite3_stmt*)stat, position, text, strlen(text), SQLITE_STATIC);
}

void Sqlite3Impl::bind(void* stat, int position, void*data, int len){
     sqlite3_bind_blob((sqlite3_stmt*)stat, position,data, len, 0);
}

void Sqlite3Impl::bind(void* stat, int position, long val, int len){
     sqlite3_bind_int((sqlite3_stmt*)stat, position, val);
}

void Sqlite3Impl::bind(void* stat, int position, double val, int len){
     sqlite3_bind_double((sqlite3_stmt*)stat, position, val);
}

void Sqlite3Impl::step(void* stat){
    sqlite3_step((sqlite3_stmt*)stat);
  //  sqlite3_finalize((sqlite3_stmt*)stat);
}

void Sqlite3Impl::exec(char* query)
{
    sqlite3_exec(database, query,0,0,0);
}

vector<vector<string> > Sqlite3Impl::query(char* query)
{

    sqlite3_stmt *statement;
    vector<vector<string> > results;

    if(sqlite3_prepare_v2(database, query, -1, &statement, 0) == SQLITE_OK)
    {
        int cols = sqlite3_column_count(statement);
        int result = 0;

        while(true)
        {
             result = sqlite3_step(statement);

             if(result == SQLITE_ROW)
             {
                 vector<string> values;
                 for(int col = 0; col < cols; col++)
                 {
                     values.push_back((char*)sqlite3_column_text(statement, col));
                 }
                 results.push_back(values);
            }

            else
            {
                 break;
            }
        }
        sqlite3_finalize(statement);
    }

    string error = sqlite3_errmsg(database);


    return results;
}
void Sqlite3Impl::close()
{
    sqlite3_close(database);
}



